package persistent.prestige.demo.netty.time;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class TimeClient {
	
	public void connect(int port, String host) throws Exception {
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(workerGroup).channel(NioSocketChannel.class)
			         .option(ChannelOption.TCP_NODELAY, true)
			         .handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel sc) throws Exception {
							sc.pipeline().addLast(new LineBasedFrameDecoder(1024))
							             .addLast(new StringDecoder())
							             .addLast(new TimeClientHandler());
						}
			        	 
					});
			
			// 发起异步连接操作
			ChannelFuture f = bootstrap.connect(host, port).sync();
			
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}
	
	private class TimeClientHandler extends ChannelHandlerAdapter {
		
		private int counter;
		private byte[] req;
		
		public TimeClientHandler() {
			req = ("Query Time Order" + System.getProperty("line.separator")).getBytes();
		}

		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			ByteBuf message = null;
			for(int i =0; i < 1; i ++) {
				message = Unpooled.copiedBuffer(req);
				ctx.writeAndFlush(message);
			}
		}

		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			String body = (String)msg;
			System.out.println("Now is : " + body + " ; the counter is" + ++counter );
			
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
			cause.printStackTrace();
			ctx.close();
		}
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			new TimeClient().connect(8080, "127.0.0.1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
